package com.anysoft.login;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.AccountLoginBean;
import com.anysoft.bean.ResultBean;
import com.anysoft.bean.UserBean;
import com.anysoft.event.FundBannerLoginEvent;
import com.anysoft.event.HomeBannerLoginEvent;
import com.anysoft.user.RetrievePwdActivity;
import com.anysoft.user.UserManageListviewActivity;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.AnalyticsEventUtils;
import com.anysoft.utils.AnalyticsUtils;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.ParamUtil;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.utils.RSACryptographyUtil;
import com.anysoft.utils.login.PicDowload;
import com.anysoft.utils.login.PictureCodeNetUtil;
import com.anysoft.web.SearchTradeNewActivity;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.anysoft.utils.BitmapUtils.getDiskBitmap;

/**
 * 头像登录
 * <p>
 * Created by wwq on 2017/2/6.
 */

public class UserIconLoginActivity extends BaseActivity {

    private static final int LOAD_CODE = 99;
    private static final int ENABLE_IMG = 98;

    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rightButton)
    Button rightButton;
    @BindView(R.id.titlebar)
    FrameLayout titlebar;
    @BindView(R.id.civ_user_icon)
    CircleImageView civUserIcon;
    @BindView(R.id.tv_icon_login_username)
    TextView tvIconLoginUsername;
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_text)
    TextView tvText;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.et_icon_login_pwd)
    EditText etIconLoginPwd;
    @BindView(R.id.tv_icon_login_forget_pwd)
    TextView tv_icon_login_forget_pwd;
    @BindView(R.id.btn_icon_login)
    Button btnIconLogin;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.iv_login_verification_code)
    ImageView ivLoginVerificationCode;
    @BindView(R.id.et_login_verification_code)
    EditText etLoginVerificationCode;
    @BindView(R.id.rl_login_verification_code)
    RelativeLayout rlLoginVerificationCode;

    private boolean isFormGestureActivity;
    private String userId = "";

    private boolean isShowPwd = false;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_icon_login);
        ButterKnife.bind(this);

        isFormGestureActivity = getIntent().getBooleanExtra(MentorConst.IS_FROM_GESTURE, false);
        userId = getIntent().getStringExtra("userId");
        rightButton.setTextSize(16);
        rightButton.setText("切换账户");
        title.setText("登录");
        UserBean userBean = findUser(userId);
        if (userBean != null) {
            String userName = userBean.getUserName();
            tvIconLoginUsername.setText(ParamUtil.formatUserName(userName));

            String pathUrl = userBean.getUserImgPath();
            if (!TextUtils.isEmpty(pathUrl)) {
                Logger.t("pathUrl").d(pathUrl);
                Bitmap bitmap = getDiskBitmap(pathUrl);
                if (bitmap != null) {
                    civUserIcon.setImageBitmap(bitmap);
                }
            } else {
                if ("0".equals(userBean.getSex())) {//女
                    civUserIcon.setImageResource(R.mipmap.icon_user_w);
                } else if ("1".equals(userBean.getSex())) {//男
                    civUserIcon.setImageResource(R.mipmap.icon_user_m);
                } else {
                    civUserIcon.setBackground(getResources().getDrawable(R.mipmap.icon_user));
                }
            }
        } else {
            civUserIcon.setBackground(getResources().getDrawable(R.mipmap.icon_user));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideLoading();
    }

    @OnClick({R.id.leftButton, R.id.rightButton, R.id.iv_right, R.id.btn_icon_login, R.id.tv_icon_login_forget_pwd,
            R.id.iv_login_verification_code, R.id.tv_login_tip})
    public void onClick(View view) {
        collapseSoftInputMethod(view.getWindowToken());
        switch (view.getId()) {
            case R.id.leftButton:
                HostConstant.SKIP_TYPE = "";
                finish();
                break;
            case R.id.rightButton:
                startActivity(new Intent().setClass(mActivity, UserManageListviewActivity.class));
                finish();
                break;
            case R.id.iv_right:
                if (isShowPwd) {
                    etIconLoginPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    isShowPwd = false;
                    ivRight.setBackgroundResource(R.mipmap.icon_eye_close);
                } else {
                    etIconLoginPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    isShowPwd = true;
                    ivRight.setBackgroundResource(R.mipmap.icon_eye);
                }
                break;
            case R.id.btn_icon_login:
                if (TextUtils.isEmpty(etIconLoginPwd.getText().toString())) {
                    showConfirmAlert(mActivity, "提示", "密码不能为空");
                    return;
                }
                if (rlLoginVerificationCode.isShown() && TextUtils.isEmpty(etLoginVerificationCode.getText().toString().trim())) {
                    showConfirmAlert(mActivity, "提示", "验证码不能为空");
                    return;
                }
                login();
                break;
            case R.id.tv_icon_login_forget_pwd:
                startActivity(new Intent().setClass(mActivity, RetrievePwdActivity.class));
                break;
            case R.id.iv_login_verification_code:
                getVerifyCode("");
                break;
            case R.id.tv_login_tip:
                selectWarmPromptByType("1");
                break;
        }
    }

    private void login() {
        showLoading(mActivity);
        String password = etIconLoginPwd.getText().toString();
        String rsaKey = getRsaKey();
        String rsaEncodePassword = "";
        if (!TextUtils.isEmpty(rsaKey)) {
            rsaEncodePassword = RSACryptographyUtil.encryptByPublicKey(password, rsaKey);
        }
        if (rlLoginVerificationCode.isShown()) {
            Map<String, String> params = new HashMap<>();
            params.put("identityType", getUserType(userId));
            params.put("identityNo", userId);
            params.put("tradePassword", rsaEncodePassword);
            params.put("identifyingCode", etLoginVerificationCode.getText().toString());

            final String loginStr = HttpUtils.createRequestUrl(this, HostConstant.LOGIN, params);
            Logger.t("-----Login_Url-----").d(loginStr);

            new Thread() {
                @Override
                public void run() {
                    // 把网络访问的代码放在这里
                    // TODO: 2017/12/21 lty .replace("+", "%2B")加这个是为了解决Http数据传输的时候将加号变为了空格
                    String json = PictureCodeNetUtil.getJsonByUrl(HostConstant.LOGIN, loginStr.split("[?]")[1].replace("+", "%2B"));
                    MentorLogger.LogJson("VerificationCodeLogin---", json);
                    UpdateJsonByVerificationCodeShow(json);
                    // String json = HttpsUtil.getMethod(login_url);
                }
            }.start();
        } else {
            Map<String, String> params = new HashMap<>();
            params.put("identityType", getUserType(userId));
            params.put("identityNo", userId);
            params.put("tradePassword", rsaEncodePassword);

            OkGo.<String>post(HostConstant.LOGIN)
                    .tag(this)
                    .params(HttpUtils.getCommonParams(this, params))
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            Log.e(TAG, "onSuccess: 头像登录");
                            hideLoading();
                            UpdateJson(response.body());
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            Log.e(TAG, "onError: 头像登录");
                            hideLoading();
                            showToast("网络加载失败，请稍后再试!");
                        }

                        @Override
                        public void onFinish() {
                            hideLoading();
                            Log.e(TAG, "onFinish: 头像登录");
                            super.onFinish();
                        }
                    });
        }
    }

    private void UpdateJson(String json) {
        hideLoading();
        AccountLoginBean bean = null;
        try {
            bean = new Gson().fromJson(json, AccountLoginBean.class);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        if (!checkState(bean, json)) {
            getVerifyCode("");
            return;
        }

        loginSuccess(bean);
    }

    private void UpdateJsonByVerificationCodeShow(String json) {
        AccountLoginBean bean;
        try {
            bean = new Gson().fromJson(json, AccountLoginBean.class);
        } catch (Exception exception) {
            showToast("数据解析异常，请联系管理员");
            return;
        }

        ResultBean resultBean = checkStateBean(bean, json);
        if (!resultBean.isSuccess()) {
            getVerifyCode(resultBean.getTip());
            return;
        }

        loginSuccess(bean);
    }

    private void loginSuccess(AccountLoginBean bean) {
        AnalyticsEventUtils.toLoginAvatarEvent(this);
        AnalyticsUtils.onAnalyticsLogin(bean.getData().getIdentityNo());

        PreferencesUtils.putBoolean(this, findUserId() + "CanGesture", true);
        if (!userId.equals(findUserId())) {
            clearSecretKey(mActivity);
        }

//        if (!isUserExist(userId) || isFormGestureActivity) {
//            Intent intent = new Intent().setClass(mActivity, SetGestureStep1Activity.class);
//            intent.putExtra(MentorConst.GET_PASSWORD, etIconLoginPwd.getText().toString());
//            startActivity(intent);
//            deleteSecretKey(mActivity, userId, 1);
//        }

        UserBean userBean = new UserBean();
        userBean.setUserName(bean.getData().getRealName());
        userBean.setUserId(userId);
        userBean.setUserType(getUserType(userId));
        userBean.setToken(bean.getData().getToken());
        userBean.setFundCustomerNo(bean.getData().getFundCustomerNo());
        userBean.setSex(bean.getData().getSex());
        saveUser(userBean, bean);
        PreferencesUtils.putString(this, MentorConst.LAST_LOGIN_USER_ID, userId);
        if ("from_redeem".equals(HostConstant.SKIP_TYPE)) {
            ActivityUtils.gotoAssetsFundActivity(this);
        } else if ("from_salary".equals(HostConstant.SKIP_TYPE)) {
            ActivityUtils.gotoFixInvestmentAllActivity(this);
        } else if ("from_query".equals(HostConstant.SKIP_TYPE)) {
            startActivity(new Intent().setClass(this, SearchTradeNewActivity.class));
        } else if ("from_home_banner".equals(HostConstant.SKIP_TYPE)) {
            EventBus.getDefault().post(new HomeBannerLoginEvent(true));
        } else if ("from_fund_banner".equals(HostConstant.SKIP_TYPE)) {
            EventBus.getDefault().post(new FundBannerLoginEvent(true));
        }
        HostConstant.SKIP_TYPE = "";
        finish();
    }

    /**
     * 获取验证码
     */
    private void getVerifyCode(String message) {
        Message msg = new Message();
        msg.what = LOAD_CODE;
        Bundle bundle = new Bundle();
        bundle.putString("message", message);
        msg.setData(bundle);
        mHandler.sendMessage(msg);
        MentorLogger.Log(TAG, "获取验证码地址：" + HostConstant.PICTURE_CHECK_CODE);
        showVerificationCode();
    }

    /**
     * 显示验证码
     */
    private void showVerificationCode() {
        String requestUrl = HostConstant.PICTURE_CHECK_CODE;
        MentorLogger.Log(TAG, "验证码请求URL：" + requestUrl);
        new PicDowload() {

            @Override
            protected void ImageDowloadedBefore() {
            }

            @SuppressWarnings("deprecation")
            @Override
            protected void ImageDowloaded(Bitmap result) {
                if (result == null) {
                    showToast("验证码获取失败，请重试");
                } else {
                    ivLoginVerificationCode.setBackgroundDrawable(new BitmapDrawable(result));
                    enableImagView();
                }

            }
        }.execute(HostConstant.PICTURE_CHECK_CODE);
    }

    /**
     * 允许点击ImageView
     */
    private void enableImagView() {
        ivLoginVerificationCode.setEnabled(true);
        Message msg = new Message();
        msg.what = ENABLE_IMG;
        msg.obj = ivLoginVerificationCode;
        mHandler.sendMessage(msg);
    }

    private Handler mHandler = new Handler() {
        @SuppressWarnings("deprecation")
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case LOAD_CODE: // 加载验证码
                    hideLoading();
                    String message = msg.getData().getString("message");
                    if (!TextUtils.isEmpty(message)) {
                        showConfirmAlert(mActivity, "提示", message);
                    }
                    rlLoginVerificationCode.setVisibility(View.VISIBLE);
                    ivLoginVerificationCode.setEnabled(false);
                    ivLoginVerificationCode.setVisibility(View.GONE);
                    break;
                case ENABLE_IMG:
                    hideLoading();
                    ((View) msg.obj).setVisibility(View.VISIBLE);
//                    rlLoginVerificationCode.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            HostConstant.SKIP_TYPE = "";
            finish();
        }
        return true;
    }
}
